package com.greatmay.webapp.action;

import java.util.List;

import com.greatmay.dao.SearchException;
import com.greatmay.model.Book;
import com.greatmay.model.Category;
import com.greatmay.model.ProductStatus;
import com.greatmay.service.BookService;
import com.greatmay.service.GenericManager;
import com.opensymphony.xwork2.Preparable;

public class BookAction extends BaseAction implements Preparable {
    private static final long serialVersionUID = -1941048473261257457L;
    private BookService bookManager;
    private GenericManager<Category, Long> categoryManager;
    private List<Category> categories;
    private List<Book> books;
    private Book book;
    private Long id;
    private String query;

    public void setBookService(BookService bookManager) {
        this.bookManager = bookManager;
    }

    public void setCategoryManager(GenericManager<Category, Long> categoryManager) {
        this.categoryManager = categoryManager;
    }

    public List<Book> getBooks() {
        return books;
    }

    public List<Category> getCategories() {
        return categories;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String bookId = getRequest().getParameter("book.id");
            if (bookId != null && !bookId.equals("")) {
                book = bookManager.get(new Long(bookId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            books = bookManager.search(query, Book.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            books = bookManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public String delete() {
        bookManager.remove(book.getId());
        saveMessage(getText("book.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            book = bookManager.get(id);
        } else {
            book = new Book();
            book.setStatus(ProductStatus.NORMAL);
        }
        categories = categoryManager.getAll();
        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (book.getId() == null);

        bookManager.save(book);

        String key = (isNew) ? "book.added" : "book.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}